package com.netty.controller;

import com.netty.Balance.ImLoadBalance;
import com.netty.im.entity.ImNode;
import com.netty.im.entity.LoginBack;
import com.netty.im.common.bean.UserDTO;
import com.netty.model.UserPO;
import com.netty.im.util.JsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


/**
 * @author 李醴茝
 */
@Api("User 相关的api")
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Resource
    private ImLoadBalance imLoadBalance;

    /**
     * 登录校验自由实现
     *
     * @param username 用户名
     * @param password 命名
     * @return 登录结果
     */
    @ApiOperation(value = "登录", notes = "根据用户信息登录")
    @RequestMapping(value = "/login/{username}/{password}", method = RequestMethod.GET)
    public String loginAction(
            @PathVariable("username") String username,
            @PathVariable("password") String password) {

        UserPO user = new UserPO();
        user.setUserName(username);
        user.setPassWord(password);
        user.setUserId(user.getUserName());

        //TODO 用户访问权限校验
        LoginBack back = new LoginBack();
        /**
         * 取得最佳的Netty服务器
         */
        ImNode bestWorker = imLoadBalance.getBestWorker();
        back.setImNode(bestWorker);
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        back.setUserDTO(userDTO);
        back.setToken(user.getUserId().toString());
        String r = JsonUtil.pojoToJson(back);
        return r;
    }


    /**
     * 从zookeeper中删除所有IM节点
     *
     * @return 删除结果
     */
    @ApiOperation(value = "删除节点", notes = "从zookeeper中删除所有IM节点")
    @GetMapping("/removeWorkers")
    public String removeWorkers() {
        imLoadBalance.removeWorkers();
        return "已经删除";
    }

}